<?php

namespace app\admin\controller\kzvote;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * @icon fa fa-circle-o
 */
class Temp extends Backend
{
    protected $noNeedRight = ['*'];

    /**
     * Vote模型对象
     * @var \app\common\model\kzvote\Vote
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\kzvote\Vote;
        $this->view->assign("moldList", $this->model->getMoldList());
        $this->view->assign("dayLimitStatusList", $this->model->getDayLimitStatusList());
        $this->view->assign("verifyStatusList", $this->model->getVerifyStatusList());
        $this->view->assign("applyStatusList", $this->model->getApplyStatusList());
        $this->view->assign("endApplyStatusList", $this->model->getEndApplyStatusList());
        $this->view->assign("groupStatusList", $this->model->getGroupStatusList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("checkList", $this->model->getCheckList());
        $this->view->assign("isOpenList", $this->model->getIsOpenList());
        $this->view->assign("applyCheckList", $this->model->getApplyCheckList());
        $this->view->assign("fansStatusList", $this->model->getFansStatusList());

        require_once ROOT_PATH . 'addons/kzvote/helper.php';
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function temp()
    {
        if ($this->request->isAjax()) {
            $list   = [
                [
                    'title' => '书法评选',
                    'name' => 'shufa',
                    'head' => '/assets/addons/kzvote/img/temp/shufa_head.png'
                ],
                [
                    'title' => '小小画家',
                    'name' => 'huajia',
                    'head' => '/assets/addons/kzvote/img/temp/huajia_head.png'
                ],
                [
                    'title' => '万能模板',
                    'name' => 'wang',
                    'head' => '/assets/addons/kzvote/img/temp/wang_head.png'
                ],
                [
                    'title' => '摄影大赛',
                    'name' => 'sheying',
                    'head' => '/assets/addons/kzvote/img/temp/sheying_head.png'
                ],
                [
                    'title' => '街舞大赛',
                    'name' => 'jiewu',
                    'head' => '/assets/addons/kzvote/img/temp/jiewu_head.png'
                ],
                [
                    'title' => '舞者风采',
                    'name' => 'fengcai',
                    'head' => '/assets/addons/kzvote/img/temp/fengcai_head.png'
                ],
                [
                    'title' => '室内设计',
                    'name' => 'sheji',
                    'head' => '/assets/addons/kzvote/img/temp/sheji_head.png'
                ],
                [
                    'title' => '琴棋书画',
                    'name' => 'qqsh',
                    'head' => '/assets/addons/kzvote/img/temp/qqsh_head.png'
                ],
                [
                    'title' => '优秀作品',
                    'name' => 'youxiu',
                    'head' => '/assets/addons/kzvote/img/temp/youxiu_head.png'
                ],
                [
                    'title' => '六一儿童节',
                    'name' => 'liuyi',
                    'head' => '/assets/addons/kzvote/img/temp/liuyi_head.png'
                ],
            ];

            $keyValue = $this->request->param('keyValue');
            if ($keyValue){
                $names = array_column($list,'name');
                $key = array_search($keyValue, $names);
                $result = array("total" => 1, "list" => $list[$key]);
                return json($result);
            }

            $result = array("total" => count($list), "list" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->where('is_temp', '1')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $link   = $this->request->post("link/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['is_temp'] = '1';
                    $params['check']   = '1';
                    $params['er_code']   = '';
                    if (isset($link['name']) && $link['name']) {
                        $params['link'] = json_encode($link);
                    } else {
                        unset($params['link']);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                    //生成小程序二维码
                    kzvote_qrCode($this->model, $this->model->id, 'pages/vote/index');
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $link   = $this->request->post("link/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if (isset($link['name']) && $link['name']) {
                        $params['link'] = json_encode($link);
                    } else {
                        unset($params['link']);
                    }
                    $result = $row->allowField(true)->save($params);
                    if (!$row->er_code){
                        //生成小程序二维码
                        kzvote_qrCode($row, $row->id, 'pages/vote/index');
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if ($this->request->isPost()) {
            (new \app\common\model\kzvote\Group())->where('vote_id', 'in', $ids)->delete();
            (new \app\common\model\kzvote\Person())->where('vote_id', 'in', $ids)->delete();
            (new \app\common\model\kzvote\Log())->where('vote_id', 'in', $ids)->delete();
        }
        parent::del();
    }

}
